﻿using HCMS.CommonDtos;
using HCMS.Entities.Base;
using HCMS.Entities.Manage;
using HCMS.Enum;
using HCMS.Extensions;
using HCMS.IServices.Base;
using HCMS.IServices.Manage;
using HCMS.Web.Manage.Filter;
using HCMS.Web.Manage.ServicesExtensions.SignalExt;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;

namespace HCMS.Web.Manage.Controllers.Module.Base
{
    /// <summary>
    /// 公告 系统
    /// </summary>
    public class NoticeController : ModuleController
    {
        private readonly INoticeAppService noticeAppService;
        private readonly INoticeReceiveAppService noticeReceiveAppService;
        private readonly IAdminAppService adminAppService;

        private readonly IHubContext<SystemMsgHub> hubContext;

        public NoticeController(
            INoticeAppService noticeAppService,
            INoticeReceiveAppService noticeReceiveAppService,
            IAdminAppService adminAppService,
            IHubContext<SystemMsgHub> hubContext
         )
        {
            this.noticeAppService = noticeAppService;
            this.noticeReceiveAppService = noticeReceiveAppService;
            this.adminAppService = adminAppService;
            this.hubContext = hubContext;
        }

        #region 列表
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult List()
        {
            return View($"{BasePath}/Base/Notice/List.cshtml");
        }

        /// <summary>
        /// 列表 Ajax
        /// </summary>
        /// <returns></returns>
        [ActionName("List")]
        [HttpPost]
        public async Task<IActionResult> PostList()
        {
            var searchArgs = new SearchArgsDto()
            {
                Status = Request.Form["status"].ToInt(9999),

                SearchName = Request.Form["searchName"].ToString(""),
                SearchKey = Request.Form["searchKey"].ToString("")
            };

            var pager = new PagerArgsDto()
            {
                CurrentPageIndex = Request.Form["page"].ToInt(1),
                PageSize = Request.Form["limit"].ToInt(10)
            };

            var result = await noticeAppService.ManageList(searchArgs, pager);

            return Json(new { code = 0, data = result.Data, count = result.PagerInfo.RowCount, msg = "ok" });
        }
        #endregion

        #region 新增、编辑、保存
        /// <summary>
        /// 新增
        /// </summary>
        /// <returns></returns>
        public IActionResult Add()
        {
            var model = new Notice()
            {
                ExpiresTime = DateTime.Parse("2099/12/31 00:00:00")
            };
            return View($"{BasePath}/Base/Notice/Edit.cshtml", model);
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> Edit(int id)
        {
            if (id <= 0)
            {
                return Content("参数无效");
            }

            var model = await noticeAppService.BaseFirstOrDefaultAsync(t => t.Id == id);
            if (model == null)
            {
                return Content($"没有找到【id：{id}】公告信息");
            }

            return View($"{BasePath}/Base/Notice/Edit.cshtml", model);
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="notice"></param>
        /// <returns></returns>
        public async Task<IActionResult> Save(Notice notice)
        {
            Notice? result = null;

            if (notice == null)
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "参数异常" });
            }
            if (string.IsNullOrWhiteSpace(notice.Title))
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "请填写 标题" });
            }
            if (string.IsNullOrWhiteSpace(notice.Content))
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "请填写 内容" });
            }

            var entity = await noticeAppService.BaseFirstOrDefaultAsync(t => t.Id == notice.Id);
            if (entity != null)
            {
                await TryUpdateModelAsync(entity);
                entity.UpdateTime = DateTime.Now;
                entity.UpdateUser = CurrentAdmin.AdminName;
                result = await noticeAppService.BaseUpdateAsync(entity);
            }
            else
            {
                entity = new Notice();
                await TryUpdateModelAsync(entity);
                entity.CreateTime = DateTime.Now;
                entity.CreateUser = CurrentAdmin.AdminName;
                entity.UpdateTime = DateTime.Now;
                entity.UpdateUser = CurrentAdmin.AdminName;

                result = await noticeAppService.BaseInsertAsync(entity);
            }

            if (result != null)
            {
                return Json(new AjaxResultDto() { Message = "处理成功" });
            }
            else
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "处理失败" });
            }
        }
        #endregion

        #region 发布
        /// <summary>
        /// 发布页
        /// </summary>
        /// <param name="id">公告 Id</param>
        /// <returns></returns>
        public async Task<IActionResult> Release(int id)
        {
            if (id <= 0)
            {
                return Content("参数无效");
            }

            var notice = await noticeAppService.BaseFirstOrDefaultAsync(t => t.Id == id);
            if (notice == null)
            {
                return Content($"没有找到【id：{id}】公告信息");
            }

            return View($"{BasePath}/Base/Notice/Release.cshtml", notice);
        }

        /// <summary>
        /// 保存 发布
        /// </summary>
        /// <returns></returns>
        [ActionName("Release")]
        [HttpPost]
        public async Task<IActionResult> SaveRelease()
        {
            var noticeId = Request.Form["noticeId"].ToInt(0);
            if (noticeId <= 0)
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "参数异常" });
            }

            var notice = await noticeAppService.BaseFirstOrDefaultAsync(t => t.Id == noticeId);
            if (notice == null)
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "没有找到公告信息" });
            }
            if (notice.Status != 0)
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "当前公告状态，无法发布。请检查是否处于【正常】状态" });
            }

            // 接收类型
            var receiveType = Request.Form["receiveType"].ToString("");
            if (string.IsNullOrWhiteSpace(receiveType))
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "请选择要接收的人员类型" });
            }
            var receiveTypeArray = Array.ConvertAll(receiveType.Split(',', StringSplitOptions.RemoveEmptyEntries), int.Parse);

            // 指定人员
            var adminIdList = new List<int>();
            var adminIds = Request.Form["adminIds"].ToString("");
            if (!string.IsNullOrWhiteSpace(adminIds))
            {
                adminIdList = Array.ConvertAll(adminIds.Split(',', StringSplitOptions.RemoveEmptyEntries), int.Parse).ToList();
            }
            if (receiveTypeArray.Contains((int)NoticeReceiveType.Admin) && adminIdList.Count == 0)
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "【指定人员】需要选择具体接收人员" });
            }

            // 指定角色
            var roleIdList = new List<int>();
            var roleIds = Request.Form["roleIds"].ToString("");
            if (!string.IsNullOrWhiteSpace(roleIds))
            {
                roleIdList = Array.ConvertAll(adminIds.Split(',', StringSplitOptions.RemoveEmptyEntries), int.Parse).ToList();
            }
            if (receiveTypeArray.Contains((int)NoticeReceiveType.Role) && roleIdList.Count == 0)
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "【指定角色】需要选择具体接收角色" });
            }

            var result = await noticeReceiveAppService.ReleaseNotice(noticeId, receiveTypeArray, adminIdList, roleIdList, CurrentAdmin.AdminName);

            if (result != null && result.Any())
            {
                // 更新公告发布时间
                notice.ReleaseTime = DateTime.Now;
                notice.UpdateTime = DateTime.Now;
                notice.UpdateUser = CurrentAdmin.AdminName;
                await noticeAppService.BaseUpdateAsync(notice);

                // 主动刷新本次接收消息的管理员客户端 消息中心
                foreach (var item in result)
                {
                    await hubContext.Clients.User(item.ToString()).SendAsync("MessageCenterRefresh", "收到新消息");
                }

                return Json(new AjaxResultDto() { Message = "发布成功" });
            }
            else
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "发布失败" });
            }
        }

        /// <summary>
        /// 获取全部管理员
        /// </summary>
        /// <returns></returns>
        [DefaultPermission]
        [HttpGet]
        public async Task<IActionResult> AllAdmin()
        {
            var query = await adminAppService.AllList();
            var adminList = query.Where(t => t.Status == 0)?.ToList();
            adminList = adminList ?? new List<Admin>();

            var result = adminList.Select(t => new
            {
                id = t.Id,
                name = t.AdminName
            }).ToList();

            return Json(result);
        }

        /// <summary>
        /// 接收记录
        /// </summary>
        /// <returns></returns>
        [DefaultPermission]
        [HttpPost]
        public async Task<IActionResult> ReceiveLogs()
        {
            var searchArgs = new SearchArgsDto()
            {
                FromId = Request.Form["fromId"].ToInt(0),

                Status = Request.Form["status"].ToInt(0),

                SearchName = Request.Form["searchName"].ToString(""),
                SearchKey = Request.Form["searchKey"].ToString("")
            };

            var pager = new PagerArgsDto()
            {
                CurrentPageIndex = Request.Form["page"].ToInt(1),
                PageSize = Request.Form["limit"].ToInt(10)
            };

            var result = await noticeReceiveAppService.ManageList(searchArgs, pager);

            return Json(new { code = 0, data = result.Data, count = result.PagerInfo.RowCount, msg = "ok" });
        }

        /// <summary>
        /// 设置公告阅读状态
        /// </summary>
        /// <returns></returns>
        [DefaultPermission]
        [HttpPost]
        public async Task<IActionResult> SetReadStatus()
        {
            var noticeId = Request.Form["noticeId"].ToInt(0);
            if (noticeId <= 0)
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "参数异常" });
            }

            var notice = await noticeAppService.BaseFirstOrDefaultAsync(t => t.Status == 0 && t.Id == noticeId);
            if (notice == null)
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "没有找到公告" });
            }

            var receive = await noticeReceiveAppService.BaseFirstOrDefaultAsync(t => t.Status == 0 && t.NoticeId == notice.Id && t.UserId == CurrentAdmin.AdminId);
            if (receive == null)
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "你没有该公告的查看权限" });
            }

            if (receive.IsRead)
            {
                return Json(new AjaxResultDto() { Message = "状态已更新" });
            }

            receive.IsRead = true;
            receive.ReadTime = DateTime.Now;
            var result = await noticeReceiveAppService.BaseUpdateAsync(receive);
            if (result != null)
            {
                return Json(new AjaxResultDto() { Message = "状态已更新" });
            }
            else
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "状态更新失败" });
            }
        }
        #endregion

    }
}
